package com.hanwei.uap.admin.web.controller;

import com.hanwei.uap.admin.config.ResultStatus;
import com.hanwei.uap.admin.domain.UserInfo;
import com.hanwei.uap.admin.model.ResultMsg;
import com.hanwei.uap.admin.repository.UserInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("user")
public class UserInfoController {
    @Autowired
    private UserInfoRepository userInforRepositoy;

    /***
     * 根据用户id，获取用户信息
     * @param id
     * @return
     */
    @RequestMapping(value = "getuser", method = RequestMethod.GET)
    public Object getUser(Long id) {
        UserInfo userEntity = userInforRepositoy.findOne(id);
        ResultMsg resultMsg = new ResultMsg(ResultStatus.SUCCESS, userEntity);
        return resultMsg;
    }

    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public UserInfo getUserById(@PathVariable Long id) {
        // 处理"/user/{id}"的GET请求，用来获取url中id值的User信息,url中的id可通过@PathVariable绑定到函数的参数中
        UserInfo userEntity = userInforRepositoy.findOne(id);
        return userEntity;
    }

    /***
     * 获取所有用户列表
     * @return
     */
    @RequestMapping(value = "getalluser", method = RequestMethod.GET)
    public Object getUserList() {
        List userEntities = (List) userInforRepositoy.findAll();
        ResultMsg resultMsg = new ResultMsg(ResultStatus.SUCCESS, userEntities);
        return resultMsg;
    }

    /***
     * 新增用户信息
     * @param userEntity
     * @return
     */
    @Modifying
    @RequestMapping(value = "adduser", method = RequestMethod.POST)
    public Object addUser(@RequestBody UserInfo userEntity) {
        userInforRepositoy.save(userEntity);
        ResultMsg resultMsg = new ResultMsg(ResultStatus.SUCCESS, userEntity);
        return resultMsg;
    }

    /***
     * 更新用户信息
     * @param userEntity
     * @return
     */
    @Modifying
    @RequestMapping(value = "updateuser", method = RequestMethod.PUT)
    public Object updateUser(@RequestBody UserInfo userEntity) {
        UserInfo user = userInforRepositoy.findOne(userEntity.getId());
        if (user != null) {
            user.setName(userEntity.getName());
            user.setAge(userEntity.getAge());
            user.setAddress(userEntity.getAddress());
            userInforRepositoy.save(user);
        }
        ResultMsg resultMsg = new ResultMsg(ResultStatus.SUCCESS, user);
        return resultMsg;
    }

    /***
     * 删除用户
     * @param id
     * @return
     */
    @Modifying
    @RequestMapping(value = "deleteuser", method = RequestMethod.DELETE)
    public Object deleteUser(Long id) {
        userInforRepositoy.delete(id);
        ResultMsg resultMsg = new ResultMsg(ResultStatus.SUCCESS, null);
        return resultMsg;
    }
}